import { createLanguageModel, createTypeScriptJsonValidator, createJsonTranslator } from 'typechat'

/**
 * request LLM
 * @param history 
 * @param modelSchema 
 * @param apiKey 
 * @returns 
 */

export const requestAI = async (
    apiKey?: string,
    history: Array<{ role: 'user' | 'assistant'; content: string }> = [],
    modelSchema?: string
) => {
    // TS上下文
    //const localSchemaPath = path.join(__dirname, 'actions.d.ts');
    //const modelSchemaContent = fs.readFileSync(localSchemaPath, 'utf-8');


    // BFF
    const modelSchemaContent = `
    /**\n* 模糊匹配actions,符合条件的action都要输返回\n*/
    export type Actions={actions:Array<Action>;};${modelSchema}
    `;

    //用户消息
    const historyContext = history.map(msg => `${msg.role}: ${msg.content}`).join('\n');

    // 调用模型接口
    const model = createLanguageModel({ DEEPSEEK_API_KEY: apiKey ?? 'sk-lwcmxewdtwykhfslcgjzppkgcwpwlzbsfiwqmppdhtlhasvw', DEEPSEEK_MODEL: 'deepseek-ai/DeepSeek-V3' });
    const validator = createTypeScriptJsonValidator<any>(modelSchemaContent, "Actions");
    const translator = createJsonTranslator(model, validator);
    const response = await translator.translate(historyContext);

    // 模型返回结果
    if (!response.success) {
        console.error('Translation failed:', response.message);
        return { error: response.message };
    }
    
    return response.data


}    